package org.je.database;

/**
 * @author fanyifeng
 */
public class DataRow
{
	private final String[]	meta;
	private final Object[]	data;

	public DataRow(String[] meta, Object[] data) {
		this.meta = meta;
		this.data = data;
	}

	/**
	 * @param i
	 * @return int
	 */
	public int getInt(int i) {
		Object o = data[i];
		if (o == null)
			return 0;
		if (o instanceof Integer) {
			return (Integer) o;
		}
		return Integer.parseInt(o.toString());
	}

	/**
	 * @param i
	 * @return int
	 */
	public long getLong(int i) {
		Object o = data[i];
		if (o == null)
			return 0;
		if (o instanceof Long) {
			return (Long) o;
		}
		if (o instanceof Integer) {
			return ((Integer) o).intValue();
		}
		return Long.parseLong(o.toString());
	}

	/**
	 * @param i
	 * @return int
	 */
	public String getStr(int i) {
		Object o = data[i];
		if (o == null)
			return null;
		return o.toString();
	}

	/**
	 * @param i
	 * @return int
	 */
	public Object getObj(int i) {
		return data[i];
	}

	/**
	 * @param name
	 * @return int
	 */
	public int getInt(String name) {
		return this.getInt(cloumnIndex(name));
	}

	/**
	 * @param name
	 * @return int
	 */
	public long getLong(String name) {
		return this.getLong(cloumnIndex(name));
	}

	/**
	 * @param name
	 * @return int
	 */
	public String getStr(String name) {
		return this.getStr(cloumnIndex(name));
	}

	/**
	 * @param name
	 * @return int
	 */
	public Object getObj(String name) {
		return getObj(cloumnIndex(name));
	}

	private int cloumnIndex(String name) {
		if (name == null) {
			throw new NullPointerException("columen-name-is-null");
		}
		for (int i = 0; i < meta.length; ++i) {
			if (meta[i].equalsIgnoreCase(name)) {
				return i;
			}
		}
		throw new RuntimeException("columen-name-cant-found: " + name);
	}

	@Override
	public String toString() {
		StringBuilder bf = new StringBuilder();
		for (Object o : data) {
			bf.append(o + "\t");
		}
		return bf.toString();
	}
}
